package com.example.lenovo.asia5b.my.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.bigkoo.pickerview.TimePickerView;
import com.example.lenovo.asia5b.home.bean.MyDataBean;
import com.example.lenovo.asia5b.home.bean.RegionBean;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.edit_email;
import static com.wushi.lenovo.asia5b.R.id.edit_real_name;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;
import static com.wushi.lenovo.asia5b.R.id.txt_birthday;
import static com.wushi.lenovo.asia5b.R.id.txt_constell;
import static com.wushi.lenovo.asia5b.R.id.txt_sex;



/**
 * Created by lenovo on 2017/6/21.
 */

public class MyDataActivity extends BaseActivity implements ICallBack {
    private LoadingDalog loadingDalog;
    //是否编辑
    private boolean isEdit = true;
    //性别对话框
    private Dialog sexDialog;
    //头像地址
    String photoFile;
    private  Spinner spr_constell,spr_address_1,spr_address_2,spr_hometown_1,spr_hometown_2;
    //地址列表
    private List<RegionBean> lists;
    //分别为地址和家乡的国家和城市名字
    private String region_name_1="",region_name_2="",hometown_name_1="",hometown_name_2="";
    //标记
    private  int region_position_1,region_position_2,isAddressFirstIn = 1,isHomeFirstIn = 1;//为1，第一次进来不显示右边完成的按钮，
    //是否修改个人资料成功过
    private boolean isSucceed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_data);
        initView();
        myInfoData();
        showConstell();

    }
    public void initView() {
        loadingDalog = new LoadingDalog(MyDataActivity.this);
        spr_constell = (Spinner)findViewById(R.id.spr_constell);
        spr_address_1 = (Spinner)findViewById(R.id.spr_address_1);
        spr_address_2= (Spinner)findViewById(R.id.spr_address_2);
        spr_hometown_1= (Spinner)findViewById(R.id.spr_hometown_1);
        spr_hometown_2= (Spinner)findViewById(R.id.spr_hometown_2);
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.my_data));
        F.id(public_btn_left).clicked(this);
        F.id(R.id.public_txt_righe).text(getResources().getString(R.string.edit));
        F.id(R.id.public_txt_righe).clicked(this);
        F.id(R.id.image_head).clicked(this);
        F.id(txt_sex).clicked(this);
        F.id(txt_birthday).clicked(this);

        F.id(R.id.public_txt_righe).visibility(View.GONE);

        F.id(R.id.edit_real_name).getEditText().setFocusable(true);
        F.id(R.id.edit_real_name).getEditText().setFocusableInTouchMode(true);
        F.id(edit_email).getEditText().setFocusable(true);
        F.id(edit_email).getEditText().setFocusableInTouchMode(true);
        F.id(R.id.edit_phone).getEditText().setFocusable(false);
        F.id(R.id.edit_phone).getEditText().setFocusableInTouchMode(false);
//        F.id(R.id.rl_constell).visibility(View.VISIBLE);
//        F.id(R.id.txt_constell).visibility(View.GONE);
        F.id(R.id.rl_address).visibility(View.VISIBLE);
        F.id(R.id.txt_address).visibility(View.GONE);
        F.id(R.id.rl_hometown).visibility(View.VISIBLE);
        F.id(R.id.txt_hometown).visibility(View.GONE);

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_change_information:
                intent = new Intent(this, ChangeInformationActivity.class);
                startActivity(intent);
                break;
            case public_btn_left:
                if (isSucceed) {
                    intent = new Intent();
                    intent.putExtra("isSucceed", isSucceed);
                    //设置返回数据
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
            case R.id.image_head :
                loadingDalog.showPhoto();
                break;
            case R.id.public_txt_righe:
                if(isEdit) {
                    //调修改接口
                    editInfoData();
                } else {
                    isEdit = true;
                    F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                    F.id(R.id.edit_nick_name).getEditText().setFocusable(true);
                    F.id(R.id.edit_nick_name).getEditText().setFocusableInTouchMode(true);
                    F.id(R.id.edit_real_name).getEditText().setFocusable(true);
                    F.id(R.id.edit_real_name).getEditText().setFocusableInTouchMode(true);
                    F.id(edit_email).getEditText().setFocusable(true);
                    F.id(edit_email).getEditText().setFocusableInTouchMode(true);
                    F.id(R.id.edit_phone).getEditText().setFocusable(false);
                    F.id(R.id.edit_phone).getEditText().setFocusableInTouchMode(false);
//                    F.id(R.id.rl_constell).visibility(View.VISIBLE);
//                    F.id(R.id.txt_constell).visibility(View.GONE);
//                    F.id(R.id.rl_address).visibility(View.VISIBLE);
//                    F.id(R.id.txt_address).visibility(View.GONE);
//                    F.id(R.id.rl_hometown).visibility(View.VISIBLE);
//                    F.id(R.id.txt_hometown).visibility(View.GONE);
                }
                break;
            case txt_sex :
                if (isEdit) {
                    showSex();
                }
                break;
            case txt_birthday:
//                if(isEdit) {
                    TimePickerView pvTime = new TimePickerView.Builder(MyDataActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date2, View v) {//选中事件回调
                            String time = getTime(date2);
                            F.id(txt_constell).text(StringUtil.constell(MyDataActivity.this,time));
                            F.id(txt_birthday).text(time);

                            isEdit=true;
                            F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                            F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                        }
                    })
                            .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                            .setCancelText(getResources().getString(R.string.qx))//取消按钮文字
                            .setSubmitText(getResources().getString(R.string.confirm))//确认按钮文字
                            .setContentSize(16)//滚轮文字大小
                            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                            .isCyclic(true)//是否循环滚动
                            .setSubmitColor(ContextCompat.getColor(MyDataActivity.this,R.color.wathet))//确定按钮文字颜色
                            .setCancelColor(ContextCompat.getColor(MyDataActivity.this,R.color.wathet))//取消按钮文字颜色
                            .setLabel(getResources().getString(R.string.n),getResources().getString(R.string.y),getResources().getString(R.string.r),
                                    getResources().getString(R.string.s),getResources().getString(R.string.f),"秒")
                            .isCenterLabel(false)
                            .build();
                    pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                    pvTime.show();
//                }

                break;
            default:
                break;
        }
    }

    Uri cameraUri = null;
    @Override
    protected void onActivityResult(int requestCode, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, arg1, data);
        switch (requestCode) {
            case 101:// 相机
//                listPicture.clear();
                if (data != null) {
                    if (data.getExtras() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    if (loadingDalog.getPhotoUrihotoUri() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                }
                // setPicture();
                break;
            case 102:// 相册返回
//                listPicture.clear();
                cameraUri = null;
                if (data != null) {
                    if (data.getData() != null) {
                        cameraUri = data.getData();
                        hear(null);
                    }else {
                        U.Toast(this, getResources().getString(R.string.system_no_getpic));
                    }
                } else if (loadingDalog.getPhotoUrihotoUri() != null) {
                    cameraUri = loadingDalog.getPhotoUrihotoUri();
                    hear(null);
                } else {
                    U.Toast(this, getResources().getString(R.string.system_no_getpic));
                }
                break;
            case 103:
                break;
        }

    }

    public void hear(Intent data) {
        Bitmap photo = null;
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                photo = bundle.getParcelable("data");
            } else if (data != null) {
                Uri uri1 = data.getData();
                try {
                    photo = MediaStore.Images.Media.getBitmap(getContentResolver(), uri1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }  else {
            try {
                photo = MediaStore.Images.Media.getBitmap(getContentResolver(), cameraUri);
                //图片太大实现压缩功能
                if (DownloadPicture.getBitmapSize(photo) > 1000800) {
                    photo = DownloadPicture.smallOneFifth(photo);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (photo == null) {
            return;
        }
        BufferedOutputStream bos = null;
        if (photo != null) {
            File dirFile = new File(Setting.IMAGE_ROOTPATH);
            if (!dirFile.exists())
                dirFile.mkdirs();
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyyMMddhhmmss", Locale.ENGLISH);
            File uploadFile = new File(dirFile + "/"
                    + sDateFormat.format(new java.util.Date())
                    + ".jpg");

            char[] chars = "0123456789abcdef".toCharArray();
            StringBuilder sb = new StringBuilder("");
            int bit;
            try {
                uploadFile.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
                photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                FileInputStream fis = new FileInputStream(uploadFile);
                byte[] b = new byte[fis.available()];
                fis.read(b);
                for (int i = 0; i < b.length; i++) {
                    bit = (b[i] & 0x0f0) >> 4;
                    sb.append(chars[bit]);
                    bit = b[i] & 0x0f;
                    sb.append(chars[bit]);
                }

                fis.close();
//                                String binary = new BigInteger(1, b).toString(16);
                photoFile = uploadFile.getAbsolutePath();
                refresh(sb.toString());
            } catch (IOException e) {
                U.Toast(MyDataActivity.this, e.getLocalizedMessage());
            } finally {
                if (bos != null) {
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int)json.getInt("State");
                        if(state == 0) {
                            String url = (String)json.getString("url");
                            //保存头像
                            UserBean bean = getUserBean();
                            bean.avatar = url;
                            SharedPreferencesUtils.setObjectToShare(bean,"user");
                            isSucceed = true;
                            //当上传图片成功时，显示头像
                            DownloadPicture.loadHearNetwork(url,F.id(R.id.image_head).getImageView());
                        }
                        else if (state == 1) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.cscw));
                        }
                    }catch (Exception e) {

                    }

                } else {
//                U.Toast(MyDataActivity.this, "数据为空");
                }
                loadingDalog.dismiss();
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject user_info = json.getJSONObject("user_info");
                            MyDataBean bean = (MyDataBean) Logic.getBeanToJSONObject(user_info,new MyDataBean());

                            String avatar =  bean.avatar;
                            F.id(R.id.txt_name).text(bean.user_name);
//                            String nickname = bean.nickname;
//                            F.id(R.id.edit_nick_name).text(nickname);

                            if (!TextUtils.isEmpty(avatar)) {
                                //保存头像
                                UserBean bean2 = getUserBean();
                                bean2.avatar = avatar;
//                                bean2.nickname = nickname;
                                bean2.mobile_phone = bean.mobile_phone;
                                SharedPreferencesUtils.setObjectToShare(bean2,"user");
                                isSucceed = true;
                                if (avatar.contains(Setting.hostUrl)) {
                                    DownloadPicture.loadHearNetwork(avatar,F.id(R.id.image_head).getImageView());
                                } else {
                                    DownloadPicture.loadHearNetwork(Setting.hostUrl+"/"+avatar,F.id(R.id.image_head).getImageView());
                                }
                            }

                            String alias = bean.alias;
                            F.id(edit_real_name).text(alias);

                            String sex = bean.sex;
                            if (sex.equals("1")) {
                                F.id(R.id.txt_sex).text(getResources().getString(R.string.man));
                            } else if (sex.equals("2")){
                                F.id(R.id.txt_sex).text(getResources().getString(R.string.woman));
                            }
                            F.id(R.id.txt_sex).getView().setTag(sex);

                            String birthday = bean.birthday;
                            F.id(R.id.txt_birthday).text(birthday);

                            String constell = bean.constell;
                            F.id(txt_constell).text(constell);

                            String live_country = bean.live_country;

                            String live_province = bean.live_province;
                            region_name_1 = live_country;
                            region_name_2 = live_province;
//                            F.id(R.id.txt_address).text(live_country+"-"+live_province);


                            String live_city = bean.live_city;

                            String home_country = bean.home_country;

                            String home_province = bean.home_province;

                            String home_city = bean.home_city;
                            hometown_name_1 = home_country;
                            hometown_name_2= home_province;
//                            F.id(R.id.txt_hometown).text(home_country+"-"+home_province);

                            String email = bean.email;
                            F.id(R.id.edit_email).text(email);

                            String mobile_phone = bean.mobile_phone;
                            F.id(R.id.edit_phone).text("+60\t\t"+StringUtil.getMobilePhone(mobile_phone));
                            //显示用户上次选择的星座
                            if(!TextUtils.isEmpty(constell)) {
                                for (int i = 0; i < spr_constell.getAdapter().getCount(); i++) {
                                    String aa = spr_constell.getAdapter().getItem(i).toString();
                                    if (aa.equals(constell)) {
                                        spr_constell.setSelection(i);
                                        break;
                                    }
                                }
                            }
                        }
                        else if (state == 1) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.cscw));
                        }
                    }catch (Exception e) {

                    }
                    F.id(edit_real_name).getEditText().setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if (hasFocus) {
                                // 获得焦点
                                isEdit=true;
                                F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                                F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
//                                F.id(edit_real_name).getEditText().clearFocus();
                            }
                        }
                    });
                    F.id(edit_email).getEditText().setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if (hasFocus) {
                                // 获得焦点
                                isEdit=true;
                                F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                                F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                            }
                        }
                    });

                } else {
//                U.Toast(MyDataActivity.this, "调用失败");
                }
                regionList();
                loadingDalog.dismiss();
            }
            if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json =  (JSONObject)result;
                        int state = (int)json.getInt("State");
                        if(state == 0) {
//                            isEdit = false;
                            F.id(R.id.public_txt_righe).visibility(View.GONE);
//                            F.id(R.id.edit_nick_name).getEditText().setFocusable(false);
//                            F.id(R.id.edit_nick_name).getEditText().setFocusableInTouchMode(false);
                            F.id(R.id.edit_real_name).getEditText().setFocusable(true);
                            F.id(R.id.edit_real_name).getEditText().setFocusableInTouchMode(true);
                            F.id(edit_email).getEditText().setFocusable(true);
                            F.id(edit_email).getEditText().setFocusableInTouchMode(true);
                            F.id(R.id.edit_phone).getEditText().setFocusable(false);
                            F.id(R.id.edit_phone).getEditText().setFocusableInTouchMode(false);
//                            F.id(R.id.rl_constell).visibility(View.GONE);
//                            F.id(R.id.txt_constell).visibility(View.VISIBLE);
//                            F.id(R.id.rl_address).visibility(View.GONE);
//                            F.id(R.id.txt_address).visibility(View.VISIBLE);
//                            F.id(R.id.rl_hometown).visibility(View.GONE);
//                            F.id(R.id.txt_hometown).visibility(View.VISIBLE);
                            UserBean bean2 = getUserBean();
                            //昵称
//                            bean2.nickname =  F.id(R.id.edit_nick_name).getText().toString();
                            SharedPreferencesUtils.setObjectToShare(bean2,"user");
                            U.Toast(MyDataActivity.this,getResources().getString(R.string.modify_succeed));
                        } else if (state == 1) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 5) {
                            U.Toast(MyDataActivity.this, getResources().getString(R.string.yxycz));
                        }
                    } catch (Exception e) {

                    }
                }else {
                    U.Toast(MyDataActivity.this,getResources().getString(R.string.modify_defeated));
                }
                loadingDalog.dismiss();
            }
            if (action == 3) {
                if (null != result && result instanceof JSONObject) {
                    if (null != result && result instanceof JSONObject) {
                        try {
                            JSONObject json = (JSONObject) result;
                            JSONArray title = json.getJSONArray("region");
                            lists = Logic.getListToBean(title,new RegionBean());
                            showAddress();
                            showHometown();
                        } catch (Exception e) {

                        }
                    }
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 上传头像
     * @param binary
     */
    public  void refresh(String binary) {
        loadingDalog.show();
        try {
            Map<String, String> formMap = new HashMap<String, String>();
            String url = Setting.UPLODE_IMAGE;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            formMap.put("user_id", user_id);
            formMap.put("time", time);
            formMap.put("sign",md5_32);
            Map<String, String> formMap2 = new HashMap<String, String>();
            formMap2.put("photo", binary);
            JsonTools2.dataHttps(this, url, formMap,formMap2, 0);
        }catch (Exception e) {
        }
    }

    /**
     * 获取个人资料接口
     */
    public void myInfoData() {
        loadingDalog.show();
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.MY_INF0;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }

    /**
     * 判断能否调用修改个人资料接口
     */
    public void editInfoData() {
        String nick_name = F.id(R.id.edit_nick_name).getText().toString();
        String alias = F.id(edit_real_name).getText().toString();
        String sex =  F.id(R.id.txt_sex).getText().toString();
        //性别1：男，2:女
        String sexID =  (String) F.id(R.id.txt_sex).getTag();
        String birthday = F.id(R.id.txt_birthday).getText().toString();
        String[] items = getResources().getStringArray(R.array.constellation);
        String constellID = "1";
        for (int i = 1; i < items.length; i++) {
            if (items[i].equals(F.id(txt_constell).getText().toString())){
                constellID = i+"";
                break;
            }
        }
        //获取住址的名字和ID
//        F.id(R.id.txt_address).text(region_name_1 +"-" + region_name_2);
        String region_id_1 = "",region_id_2= "";
        for (RegionBean bean : lists) {
            //判断第一级数
            if (region_name_1.equals(bean.region_name)){
                region_id_1 = bean.region_id;
                //判断第二级数
                for (RegionBean citys2 : bean.chile) {
                    if (region_name_2.equals(citys2.region_name)) {
                        region_id_2 = citys2.region_id;
                    }
                }
            }
        }
        //获取家乡的名字和ID
//        F.id(R.id.txt_hometown).text(hometown_name_1 +"-" + hometown_name_2);
        String hometown_id_1 = "",hometown_id_2= "";
        for (RegionBean bean : lists) {
            //判断第一级数
            if (hometown_name_1.equals(bean.region_name)){
                hometown_id_1 = bean.region_id;
                //判断第二级数
                for (RegionBean citys2 : bean.chile) {
                    if (hometown_name_2.equals(citys2.region_name)) {
                        hometown_id_2 = citys2.region_id;
                    }
                }
            }
        }
        String email =  F.id(R.id.edit_email).getText().toString();
        String phone =  F.id(R.id.edit_phone).getText().toString();
//        if (TextUtils.isEmpty(nick_name)) {
//            U.Toast(MyDataActivity.this,getResources().getString(R.string.my_data_hint_1));
//        }
//        else
            if (TextUtils.isEmpty(alias)) {
            U.Toast(MyDataActivity.this, getResources().getString(R.string.my_data_hint_8));
        }
        else if (TextUtils.isEmpty(sex)) {
            U.Toast(MyDataActivity.this, getResources().getString(R.string.my_data_hint_6));
        }
        else if (TextUtils.isEmpty(birthday)) {
            U.Toast(MyDataActivity.this, getResources().getString(R.string.my_data_hint_7));
        }
//        else if (TextUtils.isEmpty(constell)) {
//            U.Toast(MyDataActivity.this,getResources().getString(R.string.my_data_hint_9));
//        }
        else if (TextUtils.isEmpty(email)) {
            U.Toast(MyDataActivity.this,getResources().getString(R.string.my_data_hint_2));
        }
        else if (!StringUtil.checkEmail(email)) {
            U.Toast(MyDataActivity.this,getResources().getString(R.string.my_data_hint_3));
        }
        else {
            try {
                String[] birthdays = birthday.split("-");
                if(Integer.parseInt(birthdays[1]) < 10){
                    birthdays[1] = birthdays[1].replace("0","");
                }
                if(Integer.parseInt(birthdays[2]) < 10){
                    birthdays[2] = birthdays[2].replace("0","");
                }
                StringBuffer sbbirthday = new StringBuffer();
                sbbirthday.append(birthdays[0]);
                for(int i = 1; i < birthdays.length; i ++){
                    sbbirthday.append("-"+birthdays[i]);
                }
                birthday = sbbirthday.toString();
                //调用修改个人接口
                loadingDalog.show();
                Map<String, String> parmaMap = new HashMap<String, String>();
                String url = Setting.UPDA_INFO;
                String user_id = getUserBean().user_id;
                Date date = new Date();
                String time = String.valueOf(date.getTime());
                String[] sort = {"user_id"+user_id,"nickname"+nick_name,"alias"+alias,"sex"+sexID,"birthday"+birthday,
                        "constell"+constellID,"live_country"+region_id_1,"live_province"+region_id_2,"home_country"+hometown_id_1,"home_province"+hometown_id_2,
                        "email"+email,"time"+time};
                String sortStr = Logic.sortToString(sort);
                String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                parmaMap.put("user_id", user_id);
                parmaMap.put("nickname",nick_name);
                parmaMap.put("alias",alias);
                parmaMap.put("sex",sexID);
                parmaMap.put("birthday",birthday);
                parmaMap.put("constell",constellID);
                parmaMap.put("live_country",region_id_1);
                parmaMap.put("live_province",region_id_2);
                parmaMap.put("home_country",hometown_id_1);
                parmaMap.put("home_province",hometown_id_2);
                parmaMap.put("email",email);
//                parmaMap.put("mobile_phone",phone);
                parmaMap.put("time",time);
                parmaMap.put("sign",md5_32);
                JsonTools.getJsonAll(this, url, parmaMap, 2);
            }catch (Exception e) {

            }

        }
    }

    /**
     * 地址名称接口
     */
    public void regionList() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.REGION_LIST;
        JsonTools.getJsonAll(this, url, parmaMap, 3);
    }


    // 显示性别对话框
    public void showSex() {
        if (sexDialog == null) {
            View view = LayoutInflater.from(MyDataActivity.this).inflate(
                    R.layout.frame_map_photo_choose_dialog, null);
            sexDialog = new Dialog(MyDataActivity.this, R.style.transparentFrameWindowStyle);
            sexDialog.setContentView(view, new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            Window window = sexDialog.getWindow();
            window.setWindowAnimations(R.style.main_menu_animstyle);
            WindowManager.LayoutParams wl = window.getAttributes();

            Button dialog_chose_icon_camera = (Button) view
                    .findViewById(R.id.dialog_chose_icon_camera);
            Button dialog_chose_icon_photo = (Button) view
                    .findViewById(R.id.dialog_chose_icon_photo);
            Button dialog_chose_icon_cancel = (Button) view
                    .findViewById(R.id.dialog_chose_icon_cancel);
            dialog_chose_icon_camera.setText(getResources().getString(R.string.man));
            dialog_chose_icon_photo.setText(getResources().getString(R.string.woman));
            /**
             * 男
             */
            dialog_chose_icon_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    F.id(R.id.txt_sex).text(getResources().getString(R.string.man));
                    F.id(R.id.txt_sex).getView().setTag("1");
                    sexDialog.dismiss();
                    isEdit=true;
                    F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                    F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                }
            });
            /**
             * 女
             * */
            dialog_chose_icon_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    F.id(R.id.txt_sex).text(getResources().getString(R.string.woman));
                    F.id(R.id.txt_sex).getView().setTag("2");
                    sexDialog.dismiss();
                    isEdit=true;
                    F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                    F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                }
            });
            /**
             * 取消
             */
            dialog_chose_icon_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sexDialog.dismiss();
                }
            });
            wl.x = 0;
            wl.y = getWindowManager().getDefaultDisplay().getHeight();
            wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
            wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            sexDialog.onWindowAttributesChanged(wl);
            sexDialog.setCanceledOnTouchOutside(true);
        }
        sexDialog.show();
    }


    //星座选择器
    public void showConstell() {
        //第五步：为下拉列表设置各种事件的响应，这个事响应菜单被选中
        spr_constell.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
//                U.Toast(MyDataActivity.this,"您选择的是："+ adapter.getItem(arg2));
                F.id(R.id.txt_constell).text((String) arg0.getAdapter().getItem(arg2));
                int id = arg2;
                F.id(R.id.txt_constell).getView().setTag(id+"");
                /* 将mySpinner 显示*/
                arg0.setVisibility(View.VISIBLE);

//                isEdit=true;
//                F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
//                F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
        }
        });
    }
    List<String> listOne ;
    List<String> listTwo;
    private ArrayAdapter<String> adapter1,adapter2;

    //住址选择器
    public void showAddress() {
        getPriovince();
        adapter1 = new ArrayAdapter<String>(this,
                R.layout.simple_list_item,
                listOne);
        spr_address_1.setAdapter(adapter1);
        for (int i = 0; i < spr_address_1.getAdapter().getCount(); i++) {
            String aa = spr_address_1.getAdapter().getItem(i).toString();
            if (aa.equals(region_name_1)) {
                spr_address_1.setSelection(i);
                break;
            }
        }
        spr_address_1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                region_name_1 = listOne.get(arg2).trim();
                List<String> citys = getCitys(region_name_1);
                adapter2=new ArrayAdapter<String>(MyDataActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_address_2.setAdapter(adapter2);
                for (int i = 0; i < spr_address_2.getAdapter().getCount(); i++) {
                    String aa = spr_address_2.getAdapter().getItem(i).toString();
                    if (aa.equals(region_name_2)) {
                        spr_address_2.setSelection(i);
                        break;
                    }
                }
                spr_address_2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        if (isHomeFirstIn == 3 && isAddressFirstIn == 2){
                            isEdit=true;
                            F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                            F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                        }
                        isAddressFirstIn = 2;
                        region_name_2 = listTwo.get(arg2).trim();
                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    //  通过遍历集合获得市的名字 --备用赋值给Spinner1
    private void getPriovince(){
        listOne=new ArrayList<String>();
        for (RegionBean bean : lists) {
            String cityname = bean.region_name;
            listOne.add(cityname);
        }
    }

    //  通过市获得区--备用赋值给Spinner2
    private List<String> getCitys(String c_name){
        listTwo=new ArrayList<String>();
        for (RegionBean bean : lists) {
            if (c_name.equals(bean.region_name)) {
                List<RegionBean> citys = bean.chile;
                for (RegionBean citys2 : citys) {
                    String cityName = citys2.region_name;
                    listTwo.add(cityName);
                }
            }

        }
        return listTwo;
    }

    //家乡选择器
    public void showHometown() {
        adapter1 = new ArrayAdapter<String>(this,
                R.layout.simple_list_item,
                listOne);
        spr_hometown_1.setAdapter(adapter1);
        for (int i = 0; i < spr_hometown_1.getAdapter().getCount(); i++) {
            String aa = spr_hometown_1.getAdapter().getItem(i).toString();
            if (aa.equals(hometown_name_1)) {
                spr_hometown_1.setSelection(i);
                break;
            }
        }
        spr_hometown_1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                hometown_name_1 = listOne.get(arg2).trim();
                List<String> citys = getCitys(hometown_name_1);
                adapter2=new ArrayAdapter<String>(MyDataActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_hometown_2.setAdapter(adapter2);
                for (int i = 0; i < spr_hometown_2.getAdapter().getCount(); i++) {
                    String aa = spr_hometown_2.getAdapter().getItem(i).toString();
                    if (aa.equals(hometown_name_2)) {
                        spr_hometown_2.setSelection(i);
                        break;
                    }
                }
                spr_hometown_2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        hometown_name_2 = listTwo.get(arg2).trim();
                        if (isHomeFirstIn == 3 && isAddressFirstIn == 2){
                            isEdit=true;
                            F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                            F.id(R.id.public_txt_righe).text(getResources().getString(R.string.complete));
                        }
                        isHomeFirstIn = 3;

                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (isSucceed) {
                    Intent intent = new Intent();
                    intent.putExtra("isSucceed", isSucceed);
                    //设置返回数据
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
            default:
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
        return format.format(date);
    }
}
